// pages/index.js
var app       = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    form: [],
    count: 5, // 限制最大上传图片数量
    medias: [],
    current: {
      media: '',
      mailID: ''
    },
    mediasKV: '',
    discount: 100, // 折扣 100 为 100%
    unitPrice: 1, // 单价 单位元
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.page.onLoad(this)
    // this.getActivity()
    this.getMedia()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //删除图片
  deleteImage: function (event) {
    var that   = this
    var data   = this.data.form
    var index  = event.currentTarget.dataset.index
    var openId = app.WxService.getStorageSync('openid')
    if (data.length > 0) {
      if (data[index].trueUrl) {
        // 该图片已经在服务上缓存了，所以删除图片需要调用接口删除服务器那边的图片
        app.HttpService.deleteImage({
          opendId: openId,
          fileName: data[index].trueUrl
        }).then(res => {
          if (res.state == 200) {
            // 接口调用成功
            data.splice(index, 1)
            that.setData({
              form: data
            })
          }
        })
      } else {
        data.splice(index, 1)
        that.setData({
          form: data
        })
      }
    }
  },
  //添加图片
  addImages: function (event) {
    var that    = this
    var data    = this.data.form
    var count   = this.data.count
    
    if (data.length >= count) return wx.showToast({
      title: '最多只能上传' + count + '张图片',
      icon: 'none'
    })

    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        data.concat(res.tempFilePaths)
        res.tempFilePaths.forEach((n1, i1) => {
          console.log(data.length, count)
          if (data.length < count) {
            if (res.tempFiles[i1].size <= 2000000) {
              data.push({
                tempUrl: n1,
                trueUrl: ''
              })
            } else {
              return wx.showToast({
                title: '上传图片不能大于2M',
                icon: 'none'
              })
            }
          } else {
            return wx.showToast({
              title: '最多只能上传' + count + '张图片',
              icon: 'none'
            })
          }
        })

        that.setData({
          form: data
        });
      }
    })
  },
  // 图片上传
  uploadImage: function (e) {
    var that        = this
    var openId      = wx.getStorageSync('openid')
    if (!e.filePaths) {
      return false;
    }
    wx.uploadFile({
      url: "https://www.syycdz.top/base/add?openId=" + openId,
      // url: "http://192.168.2.118:7777/base/add?openId=" + wx.getStorageSync('openid'),
      filePath: e.filePaths[e.i],
      name: 'file',
      success: function (res) {
        res.data = JSON.parse(res.data);
        console.log(res.data, 'resesessese')
        if (res.data.state == 200) {
          e.i++;
          e.savePaths.push(res.data.data);
          if (e.i >= e.filePaths.length) {
            e.success(e.savePaths);
          } else {
            that.uploadImage({
              i: e.i,
              filePaths: e.filePaths,
              savePaths: e.savePaths,
              success: e.success
            });
          }
        } else {
          wx.hideLoading();
          wx.showModal({
            title: "错误",
            content: res.msg
          });
        }
      },
      fail: function (res) {
        wx.showModal({
          title: "错误",
          content: "上传图片失败"
        });
        wx.hideLoading();
      }
    })
  },
  // 图片上传2、
  // uploadImage: function(e) {
  //   wx.uploadFile({
  //     url: "http://192.168.2.112:7777/base/add?openId=" + wx.getStorageSync('openid'),
  //     filePath: e.filePaths[0],
  //     name: 'file',
  //     header: {
  //       "Content-Type": "multipart/form-data"
  //     },
  //     formData: {
  //       openId: wx.getStorageSync('openid')
  //     },
  //     success: function(res) {
  //       console.log(res)
  //     },
  //     fail: function (res) {
  //       wx.showModal({
  //         title: "错误",
  //         content: "上传图片失败"
  //       });
  //       wx.hideLoading();
  //     }
  //   })
  // },
  onSubmit(e) {
    var that       = this
    var form       = this.data.form
    var filePaths  = []
    var fileIndexs = []
    var openid     = app.WxService.getStorageSync('openid')

    // 没有授权登录    
    if (!openid) {
      return wx.showToast({
        title: '您需要登录才能打印图片',
        icon: 'none'
      })
    }

    // 没有上传过图片提示
    if (!form.length) {
      return wx.showToast({
        title: '请选择图片',
        icon: 'none'
      })
    }

    
    //循环拿出所有图片的路径，并标记好图片来源那个对象
    if (form && form.length > 0) {
      form.forEach((n1, i1) => {
        if (!n1.trueUrl) {
          filePaths.push(n1.tempUrl)
          fileIndexs.push(i1)
        }
      })
    }

    if (filePaths.length > 0) {
      console.log('有图片')
      // 上传图片
      wx.showLoading({
        title: '图片上传中',
        mask: true
      });
      
      //上传
      this.uploadImage({
        filePaths: filePaths,
        savePaths: [],
        i: 0,
        success: function (res) {
          //返回来的图片路径处理
          res.forEach((n2, i2) => {
            form[fileIndexs[i2]].trueUrl = n2
          })
          wx.hideLoading();
          
          /*图片上传完毕准备生成订单*/
          that.toPay(form)
          
          /*测试直接打印不支付*/
          // app.HttpService.print({sendId: that.data.current.mailID}).then(res => {

          // }) 
        }
      });
    } else {
      console.log('没有图片')
      that.toPay(form)
    }
  },
  // 获取活动折扣
  getActivity() {
    var that = this
    app.HttpService.getActivity().then(res => {
      if (res.state == 200) {
        that.setData({
          discount: res.data.activityMoney
        })
      }
    })
  },
  // 获取打印设备
  getMedia() {
    var that = this
    var obj  = {}
    app.HttpService.getMedia().then(res => {
      if (res.state == 200) {
        if (res.data.length) {
          res.data.forEach((n1, i1) => {
            obj[n1.username]        = n1.mailID
          })
          that.setData({
            medias:   res.data,
            mediasKV: obj,
            'current.media':  res.data[0].username,
            'current.mailID': res.data[0].mailID
          })
        } else {
          app.core.ST('暂无打印设备')
        }
      }
    })
  },
  // 获取单张打印价格
  getConfig() {
    var that  = this
    app.HttpService.getConfig({name: 'pic'}).then(res => {
      if (res.state == 200) {
        that.setData({
          unitPrice: res.data.unitPrice
        })
      }
    })
  },
  // 根据用户配置来计算价格
  getPrice() {
    var that        = this
    var { dayBalance, monthBalance, isDelete, openid }      = app.WxService.getStorageSync('Config')
    var form        = this.data.form
    var unitPrice   = this.data.unitPrice
    var discount    = this.data.discount
    var price       = 0
    form.forEach((n1, i1) => {
      var ii        = i1 + 1
      if (ii <= dayBalance) {
        price       += (unitPrice * discount)
      } else {
        price       += unitPrice
      }
    })

    return price.toFixed(2)
  },
  // 付钱二维码
  toPay(form) {
    let that        = this
    let data        = that.data
    let params
    // 此处接口为了获取每日优惠次数
    app.HttpService.wechatSignIn({ userInfo: '' }).then(res1 => {
      app.HttpService.getConfig({name: 'pic'}).then(res2 => {
        app.HttpService.getActivity().then(res3 => {
          let config = res1.data
          let unitPrice = res2.data.unitPrice
          let discount = res3.data.activityMoney
          let total
          if (config.dayBalance >= form.length) {
            total = (form.length * discount * unitPrice).toFixed(2)
            config.dayBalance = config.dayBalance - form.length
          } else {
            total = ((config.dayBalance * discount * unitPrice) + ((form.length - config.dayBalance) * unitPrice)).toFixed(2)
            config.dayBalance = 0
          }
          params = {
            total: total,
            sendId: data.current.mailID
          }
          app.HttpService.toPay(params).then(res => {
            if (res.state == 200) {
              wx.requestPayment({
                timeStamp: res.data.timeStamp,
                nonceStr: res.data.nonceStr,
                package: 'prepay_id=' + res.data.prepay_id,
                signType: 'MD5',
                paySign: res.data.sign,
                success(res) {

                },
                fail(err) {
                  console.log(err)
                },
                complete(t) {
                  "requestPayment:fail" != t.errMsg && "requestPayment:fail cancel" != t.errMsg ? (app.core.ST('支付成功'), app.WxService.setStorageSync('Config', config)) : (app.core.ST('支付失败，请重新上传图片'), app.HttpService.deleteImageAll().then(res => {
                  }))
                  that.setData({
                    form: []
                  })
                }
              })
            } else {
              that.setData({
                form: []
              })
            }
          })
        })
      })
    })
  },
  mediaChange({ detail = {} }) {
    this.setData({
      'current.media':   detail.value,
      'current.mailID':  this.data.mediasKV[detail.value]
    });
  },
})